package com.sirius.meta.mall.gateway.filter;

import com.sirius.meta.mall.gateway.exception.extend.ResultException;
import com.sirius.meta.mall.gateway.util.jwt.JWTHS256;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Objects;

/**
 * @author Surging
 * @version 1.0
 * @ClassName DecryptFilter
 * @date 2021/12/28 17:52
 * @desc 网关全局拦截器
 */
//@Slf4j
//@Component
public class DecryptFilter  {
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求体
        ServerHttpRequest request = exchange.getRequest();
        //获取路径
        RequestPath path = request.getPath();
        if(Objects.nonNull(path)){
            String pathStr = String.valueOf(path);
            pathStr = pathStr.substring(1, pathStr.length());
            try {
                Map<String, Object> stringObjectMap = JWTHS256.decryptToken(pathStr);
                String str = (String)stringObjectMap.get("value");
                pathStr = "/" + str;
//                exchange.getRequest().
            } catch (ResultException e) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                String data = "请求解析失败，禁止访问!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            } catch (Exception e) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                String data = "请求解析失败，禁止访问!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }

        }
        return chain.filter(exchange);
    }

    public int getOrder() {
        return 0;
    }
}
